<?php
/**
 * 文章
 * author：www.tong-kuai.com
 */
namespace Api\Controller;

use Think\Controller;
use Think\Exception;

class PostsController extends Controller
{

    protected $posts_model;
    protected $common_action_log_model;
//    每页条数
    protected $count = 10;

    function __construct()
    {
        parent::__construct();
        $this->posts_model = D("Portal/Posts");
        $this->common_action_log_model = D('Common/CommonActionLog');
    }

    /**
     * 根据分类id获取所有分类文章
     */
    public function getPosts()
    {
        $termId = I("get.term_id");

        $page = I('page', 1);
        $start = ($page - 1) * $this->count;

        $sql = "SELECT cp.id, cp.post_date, cp.post_title, cp.post_excerpt, cp.smeta, cp.post_status, ctagr.tag_id, ct.`name` tag_name
                FROM cmf_posts cp LEFT JOIN cmf_term_relationships ctr ON cp.id = ctr.object_id 
                LEFT JOIN cmf_tag_relationships ctagr ON cp.id = ctagr.object_id 
                LEFT JOIN cmf_tag ct ON ctagr.tag_id = ct.tag_id
                WHERE cp.post_status = 1 AND cp.post_type = 1 AND ctr.term_id = " . $termId . " GROUP BY cp.id ORDER BY cp.post_date ASC LIMIT " . $start . ',' . $this->count;
        $posts = $this->posts_model->query($sql);

        foreach ($posts as $vo) {
            $smeta = $vo['smeta'];
            $smeta = json_decode($smeta, true);
            $img = $smeta['thumb'];
            $vo['image'] = $img;
            $result[] = $vo;
        }

        exit(json_encode(array('posts' => $result)));
    }

    /**
     * 获取精选文章
     */
    public function getPostsByRecommend()
    {

        $page = I('page', 1);
        $start = ($page - 1) * $this->count;

        $sql = "SELECT cp.id, cp.post_date, cp.post_title, cp.post_excerpt, cp.smeta, cp.post_status, ctagr.tag_id, ct.`name` tag_name
                FROM cmf_posts cp LEFT JOIN cmf_term_relationships ctr ON cp.id = ctr.object_id 
                LEFT JOIN cmf_tag_relationships ctagr ON cp.id = ctagr.object_id 
                LEFT JOIN cmf_tag ct ON ctagr.tag_id = ct.tag_id
                WHERE cp.post_status = 1 AND cp.post_type = 1 AND cp.recommended = 1 GROUP BY cp.id ORDER BY cp.post_date ASC LIMIT " . $start . ',' . $this->count;
        $posts = $this->posts_model->query($sql);

        foreach ($posts as $vo) {
            $smeta = $vo['smeta'];
            $smeta = json_decode($smeta, true);
            $img = $smeta['thumb'];
            $vo['image'] = $img;
            $result[] = $vo;
        }

        exit(json_encode(array('posts' => $result)));
    }

    /**
     * 根据标签id获取文章
     */
    public function getPostsByTag()
    {
        $tagId = I("get.tag_id");

        $page = I('page', 1);
        $start = ($page - 1) * $this->count;

        $sql = "SELECT cp.id, cp.post_date, cp.post_title, cp.post_excerpt, cp.smeta, cp.post_status, ctagr.tag_id, ct.`name` tag_name
                FROM cmf_posts cp LEFT JOIN cmf_term_relationships ctr ON cp.id = ctr.object_id 
                LEFT JOIN cmf_tag_relationships ctagr ON cp.id = ctagr.object_id 
                LEFT JOIN cmf_tag ct ON ctagr.tag_id = ct.tag_id
                WHERE cp.post_status = 1 AND cp.post_type = 1 AND ct.tag_id = " . $tagId . " GROUP BY cp.id ORDER BY cp.post_date ASC LIMIT " . $start . ',' . $this->count;
        $posts = $this->posts_model->query($sql);

        foreach ($posts as $vo) {
            $smeta = $vo['smeta'];
            $smeta = json_decode($smeta, true);
            $img = $smeta['thumb'];
            $vo['image'] = $img;
            $result[] = $vo;
        }

        exit(json_encode(array('posts' => $result)));
    }

    /**
     * 根据文章id获取文章详细
     */
    public function getPostsDetail()
    {
        $postsId = I('get.postid');
        $uid = I('userid');

        $sql = "SELECT cp.id, cp.post_date, cp.post_title, cp.post_content, cp.post_excerpt, cp.post_status, ctagr.tag_id, ct.`name` tag_name, cal.id log_id FROM cmf_posts cp
                LEFT JOIN cmf_term_relationships ctr ON cp.id = ctr.object_id
                LEFT JOIN cmf_tag_relationships ctagr ON cp.id = ctagr.object_id
                LEFT JOIN cmf_tag ct ON ctagr.tag_id = ct.tag_id
                LEFT JOIN ( SELECT * FROM cmf_common_action_log ccal WHERE ccal.`user` = " . $uid . " ) cal ON cal.object = cp.id
                WHERE cp.post_status = 1 AND cp.post_type = 1 AND cp.id = " . $postsId . "  GROUP BY cp.id";
        $posts = $this->posts_model->query($sql);
        if (!empty($posts)) {
            $result = $posts[0];
        } else {
            $result = '';
        }

//        保存浏览历史
        $common_action_log_model = M("CommonActionLog");
        $where = array("user" => $uid, "object" => $postsId);
        $find_log = $common_action_log_model->where($where)->find();
        $time = time();
        if ($find_log) {
            $common_action_log_model->where($where)->save(array("count" => array("exp", "count+1"), "last_time" => $time));
        } else {
            $common_action_log_model->add(array("user" => $uid, "object" => $postsId, "last_time" => $time));
        }

        $this->returnok($result);
    }

    /**
     * 获取用户收藏
     */
    public function getFavorites()
    {
        try {
            $uid = I('userid');

            $page = I('page', 1);
            $start = ($page - 1) * $this->count;

            $user_favorites_model = M("UserFavorites");

            $sql = 'SELECT cp.post_title, cp.id post_id, cp.smeta, ct.`name` tag_name, cuf.uid,cuf.id favorite_id
                FROM cmf_posts cp
                LEFT JOIN cmf_user_favorites cuf ON cuf.object_id = cp.id
                LEFT JOIN cmf_tag_relationships ctr ON ctr.object_id = cp.id
                LEFT JOIN cmf_tag ct ON ct.tag_id = ctr.tag_id
                WHERE cp.post_status = 1 AND cp.post_type = 1 AND cuf.uid = ' . $uid . ' GROUP BY cp.id ORDER BY cp.post_date ASC LIMIT ' . $start . ',' . $this->count;

            $posts = $user_favorites_model->query($sql);
            foreach ($posts as $vo) {
                $smeta = $vo['smeta'];
                $smeta = json_decode($smeta, true);
                $img = $smeta['thumb'];
                $vo['image'] = $img;
                $result[] = $vo;
            }
            exit(json_encode(array("status" => 1, 'msg' => 'ok', 'result' => $result)));
        } catch (Exception $e) {
            exit(json_encode(array("status" => -1, 'msg' => '系统错误', 'result' => '')));
        }
    }

    /**
     * 获取用户收藏数和查看历史数
     */
    public function getUserPostDetail()
    {
        $userid = I('userid');
        $favsql = 'SELECT count(*) favorite FROM cmf_posts cp LEFT JOIN cmf_user_favorites cuf ON cuf.object_id = cp.id WHERE cp.post_type = 1 AND cp.post_status = 1 AND cuf.uid = ' . $userid;
        $logsql = 'SELECT count(*) log  FROM cmf_posts cp LEFT JOIN cmf_common_action_log ccal ON cp.id = ccal.object WHERE cp.post_type = 1 AND cp.post_status = 1 AND ccal.user = ' . $userid;
        $fav = M('Posts')->query($favsql);
        $log = M('Posts')->query($logsql);
        $this->returnok((array('fav' => $fav[0]['favorite'], 'log' => $log[0]['log'])));
    }

    /**
     * 用户收藏文章
     */
    public function collectFavorites()
    {
        $uid = I('userid');
        $postid = I('postid');
        $user_favorites_model = M("UserFavorites");
        $find_favorite = $user_favorites_model->where(array('object_id' => $postid, 'uid' => $uid))->find();
        if (!$find_favorite) {
            $post['createtime'] = time();
            $post['object_id'] = $postid;

            $post['uid'] = $uid;
            $result = $user_favorites_model->add($post);
            if ($result) {
                $this->returnok('', '收藏成功！');
            } else {
                $this->returnerror('', "收藏失败！");
            }
        } else {
            $this->returnok('', '收藏成功！');
        }

    }

    /**
     * 删除收藏
     */
    public function deleteFavorite()
    {
        $id = I("get.favoriteid", 0);
        $uid = I('userid', 0);
        $user_favorites_model = M("UserFavorites");
        $result = $user_favorites_model->where(array('id' => $id, 'uid' => $uid))->delete();
        if ($result) {
            $this->returnok('', "取消收藏成功！");
        } else {
            $this->returnerror('', "取消收藏失败！");
        }
    }

    /**
     * 返回用户历史文章
     */
    public function getActionLog()
    {
        try {
            $uid = I('userid', 0);
            $page = I('page', 1);
            $start = ($page - 1) * $this->count;

            $common_action_log_model = M("CommonActionLog");
            $sql = 'SELECT cp.id post_id, cp.post_title post_title, ct.`name` tag_name,cp.smeta
                FROM cmf_posts cp
                LEFT JOIN cmf_common_action_log ccal ON cp.id = ccal.object
                LEFT JOIN cmf_tag_relationships ctr ON ctr.object_id = cp.id
                LEFT JOIN cmf_tag ct ON ct.tag_id = ctr.tag_id
                WHERE cp.post_status = 1 AND cp.post_type = 1 AND ccal.`user` = ' . $uid . ' GROUP BY cp.id  ORDER BY cp.post_date ASC LIMIT ' . $start . ',' . $this->count;
            $find_logs = $common_action_log_model->query($sql);
            foreach ($find_logs as $vo) {
                $smeta = $vo['smeta'];
                $smeta = json_decode($smeta, true);
                $img = $smeta['thumb'];
                $vo['image'] = $img;
                $result[] = $vo;
            }
            $this->returnok($result);
        } catch (Exception $e) {
            $this->returnerror('');
        }

    }
}

